package com.example.sparkmanager.repository;

import com.example.sparkmanager.model.JobStatus;
import com.example.sparkmanager.model.SparkJob;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface SparkJobRepository extends JpaRepository<SparkJob, Long> {
    // 根据状态查找作业
    List<SparkJob> findByStatus(JobStatus status);

    // 查找特定名称的作业
    Optional<SparkJob> findByJobName(String jobName);

    // 查找状态为SCHEDULED或RUNNING的作业
    List<SparkJob> findByStatusIn(List<JobStatus> statuses);


    @Query("SELECT j FROM SparkJob j WHERE j.jobName LIKE %:name%")
    List<SparkJob> findJobsByNameContaining(@Param("name") String name);

    @Query("SELECT j FROM SparkJob j WHERE j.status = 'RUNNING' AND j.createdAt > :date")
    List<SparkJob> findRunningJobsAfterDate(@Param("date") LocalDateTime date);


    @Query(value = "SELECT * FROM spark_jobs WHERE arguments LIKE %:arg%", nativeQuery = true)
    List<SparkJob> findJobsByArgument(@Param("arg") String argument);


    List<SparkJob> findByScheduleExpressionNotNull();

    @Query("SELECT j FROM SparkJob j WHERE j.remoteJobId = :jobId")
    Optional<SparkJob> findByRemoteJobId(@Param("jobId") String jobId);

    @Modifying
    @Query("UPDATE SparkJob j SET j.status = :status WHERE j.id = :id")
    void updateJobStatus(@Param("id") Long id, @Param("status") JobStatus status);
}